package com.whz.iplocation.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.util.StringUtils;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author whz
 */
public class ThreadPoolUtils {
    private static final String TONGYU_SCHEDULED_THREAD_POOL = "tongyu-starter-thread-pool";

    public static ScheduledExecutorService asyncScheduledExecutorService(final String prefix) {
        String name = StringUtils.hasText(prefix) ? prefix : TONGYU_SCHEDULED_THREAD_POOL;
        ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(
                ThreadPoolConfig.NUM_OF_CORE,
                ThreadPoolConfig.createThreadFactory(name),
                ThreadPoolConfig.DEFAULT_ABORT_POLICY);
        service.setMaximumPoolSize(ThreadPoolConfig.NUM_OF_MAX);
        return service;
    }

    public static class ThreadPoolConfig {
        public final static int NUM_OF_CORE = Runtime.getRuntime().availableProcessors();
        public final static int NUM_OF_MAX = 2 * NUM_OF_CORE;
        public final static int QUEUE_SIZE = 10000;

        public final static ThreadPoolExecutor.AbortPolicy DEFAULT_ABORT_POLICY = new ThreadPoolExecutor.AbortPolicy();

        public static ThreadFactory createThreadFactory(final String prefix) {
            String name = prefix;
            if (!StringUtils.hasLength(name)) {
                name = "tongyu-starter-pools";
            }
            return new ThreadFactoryBuilder()
                    .setNameFormat(name + "-%d")
                    .setDaemon(true)
                    .build();
        }
    }
}